package data

import (
	"digitalhuman/internal/conf"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/go-kratos/kratos/v2/log"
	"net/http"
	"net/url"
	"strings"
)

type OssAli struct {
	BucketClient *oss.Bucket
}

func NewOssAliClientBucket(c *conf.Data) *OssAli {
	client, err := oss.New(c.OssAli.Endpoint, c.OssAli.AccessKeyId, c.OssAli.AccessKeySecret)
	if err != nil {
		log.Error(err)
		return nil
	}

	bucket, err := client.Bucket(c.OssAli.Bucket)
	if err != nil {
		log.Error(err)
		return nil
	}

	return &OssAli{BucketClient: bucket}
}

func (o *OssAli) PutObjectFromUrl(filePath string) {
	ul, err := url.Parse(filePath)
	if err != nil {
		fmt.Println(err)
		return
	}
	resp, err := http.Get(filePath)
	if err != nil {
		fmt.Println(err)
		return
	}
	mapPath := strings.Split(ul.Path, "/")
	filePutPath := "xunfei/" + mapPath[len(mapPath)-1]
	err = o.BucketClient.PutObject(filePutPath, resp.Body, oss.ContentType("audio/mpeg"))
	if err != nil {
		fmt.Println(err)
		return
	}
}

func (o *OssAli) PutObjectFromLocalFile(filePathS string) error {
	// static/1.jpg
	err := o.BucketClient.PutObjectFromFile(filePathS[2:], filePathS)
	if err != nil {
		log.Error(err)
		return err
	}

	return nil
}
